package com.example.bookappgraduation;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.example.bookappgraduation.models.Book;
import com.google.gson.Gson; // 需要添加 Gson 依赖
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class BookDetailActivity extends AppCompatActivity {

    private ImageView imageViewDetailCover;
    private TextView textViewDetailTitle, textViewDetailAuthor, textViewDetailDescription,
            textViewDetailCategory, textViewDetailPublishedTime, textViewDetailReadingInfo;
    private Button buttonReadBook, buttonToggleFavorite, buttonViewOnline;
    private Book currentBook;
    private SharedPreferences sharedPreferences;
    public static final String FAVORITES_PREF_KEY = "favorite_books";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_detail);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("书籍详情");
        }

        sharedPreferences = getSharedPreferences(LoginActivity.PREFS_NAME, MODE_PRIVATE);

        imageViewDetailCover = findViewById(R.id.imageViewDetailCover);
        textViewDetailTitle = findViewById(R.id.textViewDetailTitle);
        textViewDetailAuthor = findViewById(R.id.textViewDetailAuthor);
        textViewDetailDescription = findViewById(R.id.textViewDetailDescription);
        textViewDetailCategory = findViewById(R.id.textViewDetailCategory);
        textViewDetailPublishedTime = findViewById(R.id.textViewDetailPublishedTime);
        textViewDetailReadingInfo = findViewById(R.id.textViewDetailReadingInfo);
        buttonReadBook = findViewById(R.id.buttonReadBook);
        buttonToggleFavorite = findViewById(R.id.buttonToggleFavorite);
        buttonViewOnline = findViewById(R.id.buttonViewOnline);


        currentBook = getIntent().getParcelableExtra("book_object");

        if (currentBook != null) {
            populateBookDetails();
            updateFavoriteButtonState();
        } else {
            Toast.makeText(this, "无法加载书籍详情", Toast.LENGTH_SHORT).show();
            finish(); // 如果没有书籍数据，关闭此 Activity
        }

        buttonReadBook.setOnClickListener(v -> {
            if (currentBook != null) {
                Intent intent = new Intent(BookDetailActivity.this, BookReaderActivity.class);
                // 传递简介作为阅读内容
                String contentToRead = !TextUtils.isEmpty(currentBook.getSub2()) ? currentBook.getSub2() : "暂无摘要内容。";
                if (!TextUtils.isEmpty(currentBook.getReading()) && currentBook.getReading().contains("精彩章节节选")) {
                    contentToRead = currentBook.getReading() + "\n\n" + contentToRead;
                }
                intent.putExtra("book_title", currentBook.getTitle());
                intent.putExtra("book_content", contentToRead);
                startActivity(intent);
            }
        });

        buttonToggleFavorite.setOnClickListener(v -> {
            if (currentBook != null) {
                toggleFavoriteStatus();
            }
        });

        buttonViewOnline.setOnClickListener(v -> {
            if (currentBook != null && !TextUtils.isEmpty(currentBook.getOnline())) {
                //  online 字段是 URL，如果不是，需要解析
                String url = currentBook.getOnline();
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    // 尝试构造搜索链接
                    url = "https://search.jd.com/Search?keyword=" + Uri.encode(currentBook.getTitle());
                    Toast.makeText(this, "正在尝试打开购买页面...", Toast.LENGTH_SHORT).show();
                }
                try {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(browserIntent);
                } catch (Exception e) {
                    Toast.makeText(this, "无法打开链接", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void populateBookDetails() {
        textViewDetailTitle.setText(currentBook.getTitle());
        textViewDetailAuthor.setText(currentBook.getSub1()); // 作者和出版社
        textViewDetailDescription.setText(!TextUtils.isEmpty(currentBook.getSub2()) ? currentBook.getSub2() : "暂无简介。"); // 简介
        textViewDetailCategory.setText("分类: " + (!TextUtils.isEmpty(currentBook.getCatalog()) ? currentBook.getCatalog() : "未知"));
        textViewDetailPublishedTime.setText("出版时间: " + (!TextUtils.isEmpty(currentBook.getBytime()) ? currentBook.getBytime() : "未知"));
        textViewDetailReadingInfo.setText("阅读信息: " + (!TextUtils.isEmpty(currentBook.getReading()) ? currentBook.getReading() : "未知"));


        Glide.with(this)
                .load(currentBook.getImg())
                .placeholder(R.mipmap.ic_launcher)
                .error(R.drawable.ic_broken_image)
                .into(imageViewDetailCover);

        if (!TextUtils.isEmpty(currentBook.getOnline())) {
            buttonViewOnline.setVisibility(View.VISIBLE);
        } else {
            buttonViewOnline.setVisibility(View.GONE);
        }
    }

    private void updateFavoriteButtonState() {
        if (isFavorite(currentBook)) {
            buttonToggleFavorite.setText("从收藏移除");
        } else {
            buttonToggleFavorite.setText("添加到收藏");
        }
    }

    private void toggleFavoriteStatus() {
        List<Book> favorites = getFavoriteBooks();
        if (isFavorite(currentBook)) {
            // 从收藏中移除
            for (int i = 0; i < favorites.size(); i++) {
                // 用 title 作为唯一标识符
                if (favorites.get(i).getTitle().equals(currentBook.getTitle())) {
                    favorites.remove(i);
                    break;
                }
            }
            Toast.makeText(this, "已从收藏移除", Toast.LENGTH_SHORT).show();
        } else {
            // 添加到收藏
            favorites.add(currentBook);
            Toast.makeText(this, "已添加到收藏", Toast.LENGTH_SHORT).show();
        }
        saveFavoriteBooks(favorites);
        updateFavoriteButtonState();
    }

    private boolean isFavorite(Book book) {
        List<Book> favorites = getFavoriteBooks();
        for (Book favBook : favorites) {
            if (favBook.getTitle().equals(book.getTitle())) { // 假设 title 是唯一标识
                return true;
            }
        }
        return false;
    }



    private List<Book> getFavoriteBooks() {
        String jsonFavorites = sharedPreferences.getString(FAVORITES_PREF_KEY, null);
        if (jsonFavorites == null) {
            return new ArrayList<>();
        }
        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<Book>>() {}.getType();
        return gson.fromJson(jsonFavorites, type);
    }

    private void saveFavoriteBooks(List<Book> favorites) {
        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(favorites);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(FAVORITES_PREF_KEY, jsonFavorites);
        editor.apply();
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}